package service

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"gochat/common"
	"gochat/domain/request"
	"gochat/domain/response"
	"gochat/domain/response/result"
	"gochat/models"
	"gochat/utils"
	"gorm.io/gorm"
	"log"
)

type UserServiceImpl struct {
}

func (u *UserServiceImpl) SaveUser(c *gin.Context, reqUser request.UserRegisterRequest) {
	var user models.UserBasic
	db := common.DB
	tx := db.First(&user, "phone = ? ", reqUser.Phone)
	if tx.RowsAffected != 0 {
		result.Fail(c, 400, "手机号已存在")
		return
	}
	tx = db.First(&user, "email = ?", reqUser.Email)
	if tx.RowsAffected != 0 {
		result.Fail(c, 400, "邮箱已存在")
		return
	}

	tx = db.First(&user, "user_name = ?", reqUser.UserName)
	if tx.RowsAffected != 0 {
		result.Fail(c, 400, "用户名已存在")
		return
	}
	encoding, err := utils.Encoding(reqUser.Password)
	if err != nil {
		result.Fail(c, 500, "服务器未知异常")
		return
	}

	reqUser.Password = encoding
	user = models.UserBasic{
		Email:    reqUser.Email,
		Password: reqUser.Password,
		Phone:    reqUser.Phone,
		UserName: reqUser.UserName,
		NickName: reqUser.NickName,
	}
	if err := user.Create(db); err != nil {
		result.Fail(c, 500, "创建用户失败")
		return
	}
	result.Ok(c, "创建用户成功")
}

func (u *UserServiceImpl) UpdateUser(c *gin.Context, user models.UserBasic) {
	var oldUser models.UserBasic
	db := common.DB
	tx := db.First(&oldUser, user.ID)
	if tx.RowsAffected == 0 {
		result.Fail(c, 400, "用户不存在")
		return
	}
	oldUser.NickName = user.NickName
	oldUser.Email = user.Email
	oldUser.Phone = user.Phone
	oldUser.UserName = user.UserName
	if user.Password != "" {
		oldUser.Password = user.Password
	}
	result.Ok(c, "更新用户成功")
	if err := db.Model(&oldUser).Select("nick_name", "email", "phone", "user_name", "password").Updates(&oldUser); err != nil {
		result.Fail(c, 500, "更新用户失败")
		return
	}

}

func (u *UserServiceImpl) GetUserInfoById(c *gin.Context, uid int64) {
	db := common.DB
	var user models.UserBasic
	tx := db.First(&user, uid)
	if tx.Error != nil && errors.Is(tx.Error, gorm.ErrRecordNotFound) {
		log.Println("error:", tx.Error)
		result.Fail(c, 500, "服务器异常")
		return
	}
	if tx.RowsAffected == 0 {
		result.Fail(c, 400, "用户不存在")
		return
	}
	var userinfoReqponse response.UserInfoResponse
	err := copier.Copy(&userinfoReqponse, &user)
	if err != nil {
		log.Println(err)
		result.Fail(c, 500, "服务器异常")
		return
	}
	result.Ok(c, userinfoReqponse)
}
